module Pulse_gen
(
input					clk_in,
input					rst_n_in,
input					key_menu,
input					key_up,
input					key_down,
output					menu_state,
output	reg[1:0]				pulse_out,
//output	reg				pulse_out_pin,
output	reg[15:0]		led_misc,
output	reg[0:0]		b_led
);



//Debounce for key
wire [2:0] key_state,key_pulse;
wire [1:0] div_clko;
wire [0:0] t_bled;

breath_led breath_instance1
(
	.clk(clk_in),
	.rst_n(rst_n_in),
	.breath_led(t_bled)
);

// assign b_led = t_bled;

divide divide_uut1
(
	.clk(clk_in),
	.rst_n(rst_n_in),	.clkout(div_clko)		
);

Debounce Debounce_uut2
(
	.clk(clk_in),
	.rst_n(rst_n_in),
	.key_n(key_menu),
	.key_state(key_state[2]),
	.key_pulse(key_pulse[2])
);

Debounce Debounce_uut1
(
	.clk(clk_in),
	.rst_n(rst_n_in),
	.key_n(key_up),
	.key_state(key_state[1]),
	.key_pulse(key_pulse[1])
);

Debounce Debounce_uut0
(
	.clk(clk_in),
	.rst_n(rst_n_in),
	.key_n(key_down),
	.key_state(key_state[0]),
	.key_pulse(key_pulse[0])
);
 
wire menu_state = key_state[2];
wire up_pulse = key_pulse[1];
wire down_pulse = key_pulse[0];
 
 
reg	[3:0] cycle;
reg	[3:0] duty;
//Control cycle and duty cycle
always @(posedge clk_in or negedge rst_n_in) begin 
	if(!rst_n_in) begin 
		cycle<=4'd8;
		duty<=4'd4;
	end else begin
		if(menu_state) begin
			if(up_pulse && (cycle<4'd15)) cycle <= cycle + 4'd1;
			else if(down_pulse && (cycle>(duty+4'd1))) cycle <= cycle - 4'd1;
			else cycle <= cycle;
		end else begin
			if(up_pulse && (cycle>(duty+4'd1))) duty <= duty + 4'd1;
			else if(down_pulse && (duty>4'd0)) duty <= duty - 4'd1;
			else duty <= duty;
		end
	end 
end 
 
reg	[3:0]	cnt;
//counter for cycle
always @(posedge div_clko or negedge rst_n_in) begin 
	if(!rst_n_in) begin 
		cnt<=4'd0;
	end else begin
		if(cnt>=cycle) cnt<=4'd0;
			
			
			
		else cnt <= cnt + 4'd1;
	end 
end 
 
//pulse generate with duty
always @(posedge clk_in or negedge rst_n_in) begin 
	if(!rst_n_in) begin 
		pulse_out<=2'b11;
		//pulse_out<=1'b1;
		//pulse_out_pin<=1'b1;
	end else begin
		//if(cnt<=duty) pulse_out<=1'b1;
		if(cnt<=duty) pulse_out<=2'b11;
		else begin
			//pulse_out<=1'b0;
			pulse_out<=2'b00;
		end
	end 
end 


//led_misc 
always @(posedge clk_in or negedge rst_n_in) begin 
	if(!rst_n_in) begin 
		led_misc<=16'b0000000000000000;
		b_led <= 1'b1;
	end else begin
		led_misc<=16'b1111111111111111;
		b_led <= t_bled;
	end 
end
 
endmodule 